from rest_framework import serializers
from .models import UserFav, UserLeavingMessage, UserAddress
from rest_framework.validators import UniqueTogetherValidator
from goods.serializesr import GoodsSerializers
from shopping.settings import REGEX_MOBILE
import re


class UserFavDetailsSerializer(serializers.ModelSerializer):
    goods = GoodsSerializers()

    class Meta:
        model = UserFav
        fields = "__all__"


class UserFavSerializer(serializers.ModelSerializer):
    # 获取当前登录用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    class Meta:
        # 设置字段联合唯一性，
        validators = [
            UniqueTogetherValidator(
                queryset=UserFav.objects.all(),  # 作用域UserFav模型
                fields=('user', 'goods'),  # 作用字段
                message="已收藏",  # 如果记录已经存在则返回错误提示
            )
        ]

        model = UserFav
        fields = ('user', 'goods', 'id',)  # 序列化并返回，做删除功能必须返回ID


class LeavingMessageSerialize(serializers.ModelSerializer):
    """
    用户留言
    """
    # 指定当前用户
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    add_time = serializers.DateTimeField(read_only=True)

    class Meta:
        model = UserLeavingMessage
        fields = "__all__"


class UserAddressSerialize(serializers.ModelSerializer):
    """
    收货地址
    """
    # 指定当前用户
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    add_time = serializers.DateTimeField(read_only=True, )
    signer_mobile = serializers.CharField(label="手机号", help_text="手机号")

    # 验证手机号
    def validate_signer_mobile(self, value):

        if not re.match(REGEX_MOBILE, value):
            raise serializers.ValidationError('手机号格式错误')
        return value



    class Meta:
        model = UserAddress
        fields = '__all__'
